/*
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
 */
import { categoryGet, categoryPost } from "@/api/pro";
import ImgUpload from "@/components/img-upload";
import { CategoryType } from "@/types/pro";
import { Button, Form, Input, Select, Switch } from "antd";
import React, { useEffect, useState } from "react";

const { Option } = Select;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

const CatePub: React.FC = () => {
  const [form] = Form.useForm();
  const [cateList, setCateList] = useState<Array<CategoryType>>([]);
  useEffect(() => {
    categoryGet().then((res) => {
      let result = res.data.results.filter(
        (item: CategoryType) => item.level < 3
      );
      setCateList(result); //只渲染1、2级类目，当前项目只考虑三层类目
    });
  }, []);
  const onFinish = (values: CategoryType) => {
    console.log(values);
    let { idx } = values;
    if (idx != "0-0") {
      let { parent_id, grandparent_id, objectId } = cateList[Number(idx)];
      //录入二级
      if (parent_id == "0-0" && grandparent_id == "0-0") {
        values.level = 2;
        values.parent_id = objectId;
      }
      // 录入三级
      if (parent_id != "0-0" && grandparent_id == "0-0") {
        console.log(111111);
        values.level = 3;
        values.parent_id = objectId;
        values.grandparent_id = parent_id;
      }
    }
    delete values.idx;
    console.log(values);
    // categoryPost(values).then((res) => {
    //   console.log(res);
    // });
  };

  const onReset = () => {
    form.resetFields();
  };

  const onFill = () => {
    form.setFieldsValue({ note: "Hello world!", gender: "male" });
  };

  return (
    <Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
      <Form.Item name="name" label="分类名称" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="idx" label="父级类目" rules={[{ required: true }]}>
        <Select placeholder="请选择父级类目" allowClear>
          <Option value="0-0">顶级类目</Option>
          {cateList.map((item, index) => {
            return (
              <Option value={index} key={index}>
                {item.name}
              </Option>
            );
          })}
        </Select>
      </Form.Item>
      <Form.Item name="icon" label="分类图标" rules={[{ required: true }]}>
        <ImgUpload />
      </Form.Item>
      <Form.Item
        name="status"
        label="是否上架"
        valuePropName="checked"
        rules={[{ required: true }]}
      >
        <Switch />
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
        <Button htmlType="button" onClick={onReset}>
          重置
        </Button>
        <Button type="link" htmlType="button" onClick={onFill}>
          Fill form
        </Button>
      </Form.Item>
    </Form>
  );
};

export default CatePub;
